'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Badge } from '@/components/ui/badge'
import { Eye, EyeOff, LogIn, Users, Settings } from 'lucide-react'
import { useToast } from '@/hooks/use-toast'

// 测试账号信息
const testAccounts = [
  { username: 'admin', password: 'admin123', role: '系统管理员', description: '所有权限' },
  { username: 'procurement', password: 'proc123', role: '采购人员', description: '采购数据编辑' },
  { username: 'design', password: 'design123', role: '设计人员', description: '设计数据编辑' },
  { username: 'monitoring', password: 'mon123', role: '监测人员', description: '监测数据编辑' },
  { username: 'construction', password: 'const123', role: '施工人员', description: '施工数据编辑' },
  { username: 'build', password: 'build123', role: '建设人员', description: '建设数据编辑' },
  { username: 'operations', password: 'ops123', role: '运维人员', description: '运维数据编辑' },
  { username: 'viewer', password: 'view123', role: '查看人员', description: '只读权限' },
]

export default function LoginPage() {
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [showPassword, setShowPassword] = useState(false)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [showTestAccounts, setShowTestAccounts] = useState(false)
  const router = useRouter()
  const { toast } = useToast()

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)
    setError('')

    try {
      const response = await fetch('/api/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ username, password }),
      })

      const data = await response.json()

      if (data.success) {
        // 保存用户信息到localStorage
        localStorage.setItem('currentUser', JSON.stringify({
          id: data.data.user.id,
          username: data.data.user.username,
          full_name: data.data.user.full_name,
          role: data.data.user.role_code,
          role_name: data.data.user.role_name
        }))

        toast({
          title: "登录成功",
          description: `欢迎回来，${data.data.user.full_name}！`,
        })

        // 根据用户角色跳转
        if (data.data.user.role_code === 'A') {
          router.push('/admin')
        } else {
          router.push('/')
        }
      } else {
        setError(data.error || '登录失败')
      }
    } catch (error) {
      console.error('登录失败:', error)
      setError('登录失败，请稍后重试')
    } finally {
      setLoading(false)
    }
  }

  const quickLogin = (account: typeof testAccounts[0]) => {
    setUsername(account.username)
    setPassword(account.password)
    setShowTestAccounts(false)
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 flex items-center justify-center p-4">
      <div className="w-full max-w-md">
        {/* 登录表单 */}
        <Card className="w-full">
          <CardHeader className="space-y-1">
            <CardTitle className="text-2xl font-bold text-center">系统登录</CardTitle>
            <CardDescription className="text-center">
              请输入您的用户名和密码登录系统
            </CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="username">用户名</Label>
                <Input
                  id="username"
                  type="text"
                  placeholder="请输入用户名"
                  value={username}
                  onChange={(e) => setUsername(e.target.value)}
                  required
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="password">密码</Label>
                <div className="relative">
                  <Input
                    id="password"
                    type={showPassword ? "text" : "password"}
                    placeholder="请输入密码"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    required
                  />
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
                    onClick={() => setShowPassword(!showPassword)}
                  >
                    {showPassword ? (
                      <EyeOff className="h-4 w-4" />
                    ) : (
                      <Eye className="h-4 w-4" />
                    )}
                  </Button>
                </div>
              </div>

              {error && (
                <Alert variant="destructive">
                  <AlertDescription>{error}</AlertDescription>
                </Alert>
              )}

              <Button type="submit" className="w-full" disabled={loading}>
                {loading ? (
                  <div className="flex items-center space-x-2">
                    <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                    <span>登录中...</span>
                  </div>
                ) : (
                  <div className="flex items-center space-x-2">
                    <LogIn className="h-4 w-4" />
                    <span>登录</span>
                  </div>
                )}
              </Button>

              {/* 测试账号按钮 */}
              <div className="pt-4 border-t">
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setShowTestAccounts(!showTestAccounts)}
                  className="w-full flex items-center space-x-2"
                >
                  <Users className="h-4 w-4" />
                  <span>测试账号</span>
                </Button>

                {showTestAccounts && (
                  <div className="mt-4 space-y-2">
                    {testAccounts.map((account) => (
                      <Button
                        key={account.username}
                        type="button"
                        variant="ghost"
                        onClick={() => quickLogin(account)}
                        className="w-full justify-start text-left h-auto p-3"
                      >
                        <div className="w-full">
                          <div className="flex items-center justify-between">
                            <div>
                              <div className="font-medium text-sm">{account.role}</div>
                              <div className="text-xs text-gray-500">@{account.username}</div>
                            </div>
                            <div className="text-right">
                              <Badge variant="outline" className="text-xs">
                                {account.password}
                              </Badge>
                              <div className="text-xs text-gray-500 mt-1">{account.description}</div>
                            </div>
                          </div>
                        </div>
                      </Button>
                    ))}
                    
                    <div className="mt-4 p-3 bg-blue-50 rounded-lg">
                      <div className="flex items-center space-x-2 text-blue-800 mb-2">
                        <Settings className="h-4 w-4" />
                        <span className="text-sm font-medium">管理员功能</span>
                      </div>
                      <p className="text-xs text-blue-700">
                        使用 admin 账号登录可访问用户管理和角色管理功能
                      </p>
                    </div>
                  </div>
                )}
              </div>
            </form>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}